package com.kh.controller;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kh.pojo.AjaxJson;
import com.kh.pojo.KHUser;
import com.kh.service.UserService;
import com.kh.utils.UserUtils;

@Controller
@RequestMapping("loginController")
public class LoginController {
	@Autowired
	UserService userService;

	public static final String goLogin = "loginController.do?goLogin";
	public static final String homeUrl="kit_admin/index";
	public static final String home="loginController.do?home";

	// http://localhost:1234/learn/loginController.do?goLogin
	@RequestMapping(params = "goLogin")
	public String goLogin(KHUser user,HttpSession session,HttpServletRequest request) {

		KHUser sessionUser = UserUtils.getUser();
		if(sessionUser!=null) {
			return "redirect:"+home;
		}
		return "kit_admin/login";
	}

	@RequestMapping(params="doLogin")
	@ResponseBody
	public AjaxJson doLogin(KHUser user) {
		AjaxJson ajaxJson=new AjaxJson();
		ajaxJson.setCode(AjaxJson.ok);
		List<KHUser> userList = userService.getUserList(user);
		if (!userList.isEmpty()) {
			UserUtils.setUser(userList.get(0));
		} else {
			// 不存在用户
//			return "redirect:" + goLogin;
			ajaxJson.setCode(-1);
			ajaxJson.setMessage("用户不存在,或者密码错误");
		}
		return ajaxJson;
	}
	// http://localhost:1234/learn/loginController.do?home
	@RequestMapping(params = "home")
	public String doLogin(KHUser user, HttpSession session, HttpServletRequest request) {

		// KHUser sessionUser = (KHUser) session.getAttribute(UserUtils.KH_USER);
		KHUser sessionUser = UserUtils.getUser();
		System.out.println("sessionUser::" + sessionUser);
		if (StringUtils.isEmpty(user.getStaffNo()) && null == sessionUser) {
			request.setAttribute("msg", "用户工号为空");
			return "redirect:" + goLogin;
		}
		return homeUrl;
	}

	@RequestMapping(params = "logout")
	@ResponseBody
	public AjaxJson logout(HttpSession session) {
		AjaxJson ajaxJson=new AjaxJson();
		// session.setAttribute(UserUtils.KH_USER, null);
		Enumeration<String> em = session.getAttributeNames();
		while (em.hasMoreElements()) {
			session.removeAttribute(em.nextElement().toString());
		}
		ajaxJson.setCode(AjaxJson.ok);
		return ajaxJson;
//		return "redirect:" + goLogin;
	}

	@RequestMapping(params = "test")
	public String test(HttpServletRequest request) {
		request.setAttribute("msg", "测试一下");
		return "home/test";
	}

}
